package main

import (
	"fmt"
	"sync"
)

// 使用goroutin和channle
// 1.定义channle
// 2.开启goroutin去监听channle
// 3.往channle中添加值
// 4.goroutin去获取channle中的值并处理逻辑
func worker(id int, jobs <-chan int, results chan<- int) {
	//读取jobs中的数据进行数据操作,如果没有值channle会一直阻塞
	for j := range jobs {
		fmt.Printf("worker %d started job %d\n", id, j)
		// 模拟耗时操作
		// ...
		fmt.Printf("worker %d finished job %d\n", id, j)
		results <- j * 2
	}
}

func main() {
	const numJobs = 5

	jobs := make(chan int, numJobs)
	results := make(chan int, numJobs)

	var wg sync.WaitGroup

	// 启动3个goroutines来处理任务
	for w := 1; w <= 3; w++ {
		wg.Add(1)
		go func(id int) {
			defer wg.Done()
			worker(id, jobs, results)
		}(w)
	}

	// 发送任务
	for j := 1; j <= numJobs; j++ {
		jobs <- j
	}
	close(jobs)

	// 等待所有任务完成
	wg.Wait()
	close(results)

	// 收集结果
	for a := 1; a <= numJobs; a++ {
		fmt.Println(<-results)
	}
}
